<template>
  <a-modal
    :open="props.modelVisible"
    title="产线编辑"
    :footer="null"
    @cancel="cancel"
    width="95%"
    wrap-class-name="full-modal"
    centered
  >
    <a-spin
      :spinning="spinning"
      size="large"
      style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%)"
    />
    <div class="container">
      <div class="left-container">
        <!-- 左侧内容 -->
        <div class="edit">
          <div class="edit-header">
            <a-input
              v-model:value="lineName"
              @blur="updateLineName(lineName)"
              style="width: 70%; margin-right: 10px"
            />
            <div class="edit-header-buttonGroup">
              <a-popconfirm
                title="确实删除该产线？"
                ok-text="是"
                cancel-text="否"
                @confirm="deleteLine"
              >
                <a-button type="primary" danger>删除产线</a-button>
              </a-popconfirm>

              <a-button type="primary" @click="updateLineAssignment()">确认修改</a-button>
            </div>
          </div>
          <a-divider style="margin: 10px" />
          <!-- 筛选栏 -->
          <div class="filter">
            <a-form
              ref="formRef"
              :model="formState"
              layout="inline"
              :label-col="{ style: { width: '80px' } }"
              AutoComplete="off"
            >
              <a-form-item label="任务类型" name="taskType">
                <a-select
                  ref="select"
                  v-model:value="formState.taskType"
                  style="width: 100px"
                  @change="findTask()"
                  placeholder="筛选类型"
                  :options="typeOptions"
                  allow-clear
                ></a-select>
              </a-form-item>
              <a-form-item label="所属课程" name="course" v-if="projectType == 2">
                <a-select
                  ref="select"
                  v-model:value="formState.course"
                  style="width: 200px"
                  @change="findTask()"
                  :fieldNames="{ label: 'courseName', value: 'courseId' }"
                  allow-clear
                  placeholder="筛选课程"
                  :options="courseList"
                ></a-select>
              </a-form-item>
            </a-form>
            <a-button @click="addRow" style="float: right; margin-right: 10px">新增节点</a-button>
          </div>

          <div class="edit-body">
            <a-empty
              style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%)"
              v-if="!dynamicValidateForm.rows.length && !spinning"
            />
            <div>
              <!-- 行列表 -->
              <a-form ref="dynamicValidateFormRef" :model="dynamicValidateForm" v-if="!spinning">
                <div v-for="(row, index) in dynamicValidateForm.rows" :key="row.order" class="row">
                  <a-form-item>
                    <span
                      style="margin: 0 40px 0 20px; font-size: 18px; font-weight: 500; color: #333"
                    >
                      {{ row.order }}
                    </span>
                  </a-form-item>

                  <a-form-item
                    :name="['rows', index, 'taskId']"
                    :rules="[{ required: true, message: '', trigger: 'change' }]"
                  >
                    <a-select
                      ref="select"
                      v-model:value="row.taskId"
                      style="width: 200px"
                      @change="(value, option) => findAssignments(option, row, index)"
                      :fieldNames="{ label: 'taskName', value: 'taskId' }"
                      allow-clear
                      placeholder="选择任务"
                      :options="taskList[index]"
                    >
                    </a-select>
                  </a-form-item>
                  <a-form-item
                    :name="['rows', index, 'assignmentId']"
                    :rules="{
                      required: true,
                      message: '', // 设置为空字符串以移除提示语句
                      trigger: 'change'
                    }"
                  >
                    <a-select
                      ref="select"
                      v-model:value="row.assignmentId"
                      style="width: 400px"
                      allow-clear
                      @change="setLine(row, index)"
                      @focus="findAssignmentsByRow(row, index)"
                      placeholder="选择分配对象"
                    >
                      <a-select-option
                        v-for="assignment in assignmentList[index]"
                        :value="assignment.assignmentId"
                      >
                        {{ assignment.teamName ? assignment.teamName : '默认组' }} -
                        <span v-for="user in assignment.userList">
                          {{ user.userName + ' ' }}
                        </span>
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-button @click="removeRow(row.order, index)">删除</a-button>
                </div>
              </a-form>
            </div>
          </div>
        </div>
      </div>

      <!-- 分界线 -->
      <a-divider type="vertical" class="divider" />
      <div class="right-container">
        <div class="line-box">
          <a-timeline>
            <a-timeline-item
              v-for="row in dynamicValidateForm.rows"
              :color="getColor(row.assignmentStatus)"
            >
              <template #dot>
                <ClockCircleOutlined style="font-size: 18px" />
              </template>
              <p>{{ row.taskName == null ? '' : '任务名称：' + row.taskName }}</p>
              <div style="display: flex; margin-bottom: 14px">
                <template v-if="row.userList != null">
                  <p style="white-space: nowrap">承担人员：</p>
                </template>
                <div style="display: flex; flex-wrap: wrap">
                  <span v-for="user in row.userList" :key="user.id" style="margin-right: 5px">
                    {{ user.userName }}
                  </span>
                </div>
              </div>
              <p>
                {{
                  row.endTime == null
                    ? ''
                    : '截至日期：' + dayjs(row.endTime).format('YYYY年MM月DD日 HH:mm:ss')
                }}
              </p>
            </a-timeline-item>
            <a-timeline-item v-if="dynamicValidateForm.rows.length">
              <template #dot>
                <ClockCircleOutlined style="font-size: 18px" />
              </template>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import dayjs, { Dayjs } from 'dayjs';
import LineDao from '@/daos/line_dao';
import TaskDao from '@/daos/task_dao';
import { message } from 'ant-design-vue';
const taskDao = new TaskDao();
const lineDao = new LineDao();
const store = useStore();
const route = useRoute();

const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  lineId: {
    type: Number
  }
});
const emit = defineEmits(['update:modelVisible', 'confirm']);
// 定义行的数据结构
interface Row {
  order: number; // 顺序
  taskId: number; // 任务ID
  taskName: string; //任务名称
  teamName: string; //小组名称
  userList: any; //承担者列表
  assignmentStatus: number; //分配状态
  endTime: Dayjs; //截止日期；
  assignmentId: number; //分配ID
}
//加载状态
const spinning = ref(true);
//产线名称
const oldLineName = ref();
const lineName = ref();
//判断是否未为项目式教学项目
const projectType = store.getters.projectType;
//项目ID
const projectId = Number(route.params.projectId);
//任务列表
const tasks = ref();
const taskList = ref([]);
//分配记录列表
const assignmentList = ref([]);
//课程列表
const courseList = store.getters.courseList;
//筛选表单参数
const formRef = ref();
const formState = reactive({
  taskType: null,
  course: undefined
});
//节点选项
const dynamicValidateFormRef = ref();
const dynamicValidateForm = reactive<{ rows: Row[] }>({
  rows: []
});
const typeOptions = ref([
  {
    value: 1,
    label: '需求任务'
  },
  {
    value: 2,
    label: '开发任务'
  },
  {
    value: 3,
    label: '测试任务'
  },
  {
    value: 4,
    label: '缺陷任务'
  },
  {
    value: 0,
    label: '课程任务',
    disabled: projectType != 2
  }
]);

//查询任务
const findTask = async () => {
  const result = await taskDao.findTasksByProjectId(
    projectId,
    null,
    formState.taskType,
    formState.course,
    null,
    null,
    1,
    999
  );
  tasks.value = result.data.data.rows;
  for (let i = 0; i < dynamicValidateForm.rows.length; i++) {
    taskList.value[i] = result.data.data.rows;
    await findAssignmentsByRow(dynamicValidateForm.rows[i], i);
  }
  spinning.value = false;
};
//获取单个任务所有分配记录
const findAssignments = async (option, row, index) => {
  if (option != null) {
    row.taskName = option.taskName;
    const result = await taskDao.findAssignmentsByTaskId(row.taskId, projectType);
    assignmentList.value[index] = result.data.data;
    row.assignmentId = null;
    row.userList = null;
    row.endTime = null;
  } else {
    row.taskId = null;
    row.taskName = null;
    row.assignmentId = null;
    row.userList = null;
    row.endTime = null;
    assignmentList.value[index] = null;
  }
};
const findAssignmentsByRow = async (row, index) => {
  if (row.taskId != null) {
    const result = await taskDao.findAssignmentsByTaskId(row.taskId, projectType);
    assignmentList.value[index] = result.data.data;
  } else {
    message.info('未选择任务无法获取分配记录');
    row.assignmentId = null;
    row.userList = null;
    row.endTime = null;
    assignmentList.value[index] = null;
  }
};
// 添加一行
const addRow = () => {
  const newRow: Row = {
    order: dynamicValidateForm.rows.length + 1, // 行号递增
    taskId: null,
    taskName: undefined,
    teamName: undefined,
    assignmentStatus: undefined,
    endTime: undefined,
    assignmentId: null,
    userList: undefined
  };
  dynamicValidateForm.rows.push(newRow);
  taskList.value.push(tasks.value);
};

// 删除一行
const removeRow = (order: number, index) => {
  dynamicValidateForm.rows = dynamicValidateForm.rows.filter((row) => row.order !== order);
  // 更新行号
  dynamicValidateForm.rows.forEach((row, index) => {
    row.order = index + 1;
  });
  assignmentList.value[index] = null;
};

//获取节点颜色
const getColor = (assignmentStatus) => {
  if (assignmentStatus == 0) return 'gray'; //待领取
  else if (assignmentStatus == 1) return 'blue'; //进行中
  else if (assignmentStatus == 2) return '#FADA5E'; //待批阅
  else return 'green'; //已完成
};
//更新右侧产线图
const assignment = ref();
const setLine = (row, index) => {
  if (row.assignmentId != null) {
    assignment.value = assignmentList.value[index].find(
      (item) => item.assignmentId === row.assignmentId
    );
    row.userList = assignment.value.userList;
    row.endTime = assignment.value.endTime;
    row.assignmentStatus = assignment.value.assignmentStatus;
  } else {
    row.userList = null;
    row.endTime = null;
    assignment.value = null;
  }
};
//更新项目产线
const updateLineAssignment = () => {
  formRef.value
    .validate()
    .then(async () => {
      const result = await lineDao.updateLineAssignment(props.lineId, dynamicValidateForm.rows);
      message.success(result.data.data);
      emit('confirm');
    })
    .catch((error) => {
      message.error('节点不能为空');
    });
};
//删除产线
const deleteLine = async () => {
  const result = await lineDao.deleteLine(props.lineId);
  message.success(result.data.data);
  emit('confirm');
  emit('update:modelVisible', false);
};
//查询产线
const findLineByLineId = async () => {
  const result = await lineDao.findLineByLineId(props.lineId);
  lineName.value = result.data.data.lineName;
  oldLineName.value = result.data.data.lineName;
  dynamicValidateForm.rows = result.data.data.assignmentDtoList;
};
//更新产线名称
const updateLineName = async (lineName) => {
  if (lineName === oldLineName.value) {
  } else {
    const result = await lineDao.updateLineName(props.lineId, lineName);
    message.success(result.data.data);
    emit('confirm');
  }
};
const cancel = () => {
  emit('update:modelVisible');
  formRef.value.resetFields();
  dynamicValidateForm.rows = [];
  lineName.value = '';
};
watch(
  () => props.modelVisible,
  () => {
    if (props.modelVisible == true) {
      spinning.value = true;
      findLineByLineId();
      findTask();
    }
  }
);
</script>

<style scoped>
.container {
  background: #ffffffff;
  display: flex;
  flex-direction: row;
  height: 100%;
  width: 100%;
  gap: 16px;
  min-width: 960px;
  min-height: 540px;
}

.left-container {
  background: rgba(18, 65, 255, 0.1);
  width: 75%;
  height: 100%;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.right-container {
  background: rgba(18, 65, 255, 0.1);
  width: 25%;
  min-width: 300px;
  height: 100%;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.line-box {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
  overflow: auto;
}

.edit {
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.edit-header {
  display: flex;
  width: 100%;
}

.edit-body {
  position: relative;
  width: 100%;
  height: 85%;
  overflow-y: auto;
}

.edit-header-buttonGroup {
  width: 30%;
  display: flex;
  justify-content: space-around;
}

.divider {
  height: 100%;
  margin: 1px;
  background: rgba(18, 65, 255, 0.1);
}

.filter {
  display: flex;
}

.row {
  margin: 10px 10px;
  padding: 15px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 800px;
}

button {
  margin-left: auto;
  cursor: pointer;
}

.ant-form-item {
  margin-bottom: 0;
}

.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 20px;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(95vh);
  }

  .ant-modal-body {
    flex: 1;
    overflow: auto;
    padding: 5px;
  }
}
</style>
